<script setup lang="ts">
import type { FinanceExpenseReimbursement } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getFinanceAttachmentByPage, getFinanceExpenseReimbursementById } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { getStatusName } from '@/constants/enums'
import { useFlow } from '@/hooks/useFlow'
import useLoading from '@/hooks/useLoading'
import { useSystemStore } from '@/store/system'
import { formatDate } from '@/utils/timeUtils'

definePage({
  style: {
    navigationBarTitleText: '费用报销详情',
    backgroundColor: '#f5f5f5',
    enablePullDownRefresh: true,
  },
})

// 获取页面参数
const processInstanceId = ref<string>('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 使用系统 store
const systemStore = useSystemStore()

// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  loading: flowLoading,
  getCurrentUserPendingTaskId,
} = useFlow()

// 业务ID
const businessId = computed(() => {
  if (currentProcess.value?.businessKey) {
    return currentProcess.value.businessKey
  }
  if (currentProcess.value?.formVariables?.BUSINESS_KEY) {
    return currentProcess.value.formVariables.BUSINESS_KEY
  }
  return ''
})

// 费用报销详情数据
const reimbursementData = ref<FinanceExpenseReimbursement | null>(null)
const { loading: detailLoading, startLoading: startDetailLoading, endLoading: endDetailLoading } = useLoading(false)
const error = ref(false)

// 整体加载状态（包括流程和详情）
const loading = computed(() => flowLoading.value || detailLoading.value)

// 发票类型映射
const invoiceTypeMap = computed(() => {
  const dict = systemStore.invoiceTypeDict
  const map: Record<number, string> = {}
  dict.forEach((item) => {
    map[Number(item.value)] = item.label
  })
  return map
})

// 获取流程实例信息
async function fetchProcessInfo(id: string) {
  try {
    await getProcessInstance(id)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 流程信息获取成功后，自动获取业务详情
    if (businessId.value) {
      await fetchReimbursementDetail(businessId.value)
    }
  }
  catch (error) {
    console.error('获取流程信息失败:', error)
    uni.showToast({
      title: '获取流程信息失败',
      icon: 'none',
    })
  }
}

// 获取费用报销详情数据
async function fetchReimbursementDetail(id?: string) {
  const reimbursementId = id || businessId.value
  if (!reimbursementId)
    return

  startDetailLoading()
  error.value = false

  try {
    const data = await getFinanceExpenseReimbursementById(reimbursementId)
    reimbursementData.value = data.data || null
    // 根据费用明细id获取对应的发票附件
    if (reimbursementData.value.detailList) {
      reimbursementData.value.detailList.forEach(async (detail, index) => {
        // 获取发票附件
        const invoiceAttachments = await getFinanceAttachmentByPage({
          timestamp: Date.now(),
          applicationId: detail.id,
          applicationType: '报销发票',
        })
        // 获取附件
        const attachments = await getFinanceAttachmentByPage({
          timestamp: Date.now(),
          applicationId: detail.id || '',
          applicationType: '报销',
        })
        detail.invoiceAttachments = invoiceAttachments.data?.records || []
        detail.financeAttachmentList = attachments.data?.records || []
      })
    }
  }
  catch (err) {
    console.error('获取费用报销详情失败:', err)
    error.value = true
  }
  finally {
    endDetailLoading()
  }
}

// 基本信息
const basicInfo = computed<InfoItem[]>(() => {
  if (!reimbursementData.value)
    return []

  return [
    {
      label: '报销单号',
      value: reimbursementData.value.expenseNo || '-',
      key: 'expenseNo',
    },
    {
      label: '报销人',
      value: reimbursementData.value.applicantName || '-',
      key: 'applicantName',
    },
    {
      label: '报销部门',
      value: reimbursementData.value.businessDepartmentName || '-',
      key: 'businessDepartmentName',
    },
    {
      label: '提交时间',
      value: formatDate(reimbursementData.value.submitTime as string, 'datetime_short'),
      key: 'submitTime',
      type: 'date',
    },
    {
      label: '报销事由',
      value: reimbursementData.value.description || '-',
      key: 'description',
      forceMultiline: true,
    },
  ]
})

// 费用明细列表
const expenseDetailCards = computed<InfoItem[][]>(() => {
  if (!reimbursementData.value?.detailList)
    return []

  return reimbursementData.value.detailList.map((item, index) => [

    {
      label: '费用类型',
      value: item.name || '-',
      key: `detail-${item.id || index}-name`,
    },
    {
      label: '费用金额',
      value: item.amount,
      key: `detail-${item.id || index}-amount`,
      type: 'currency',
    },
    {
      label: '所属机构',
      value: item.institutionName || '-',
      key: `detail-${item.id || index}-institutionName`,
    },
    {
      label: '所属部门',
      value: item.departmentName || '-',
      key: `detail-${item.id || index}-departmentName`,
    },
    {
      label: '事由',
      value: item.reason || '-',
      key: `detail-${item.id || index}-reason`,
      forceMultiline: true,
    },
    {
      label: '发票类型',
      value: invoiceTypeMap.value[item.invoiceType || 0] || '-',
      key: `detail-${item.id || index}-invoiceType`,
    },
    {
      label: '发票附件',
      value: item.invoiceAttachments || '-',
      key: `detail-${item.id || index}-invoiceAttachments`,
      slot: 'invoiceAttachments',
      forceMultiline: true,
    },
  ])
})

// 报销信息
const reimbursementInfo = computed<InfoItem[]>(() => {
  if (!reimbursementData.value)
    return []

  return [
    {
      label: '报销金额',
      value: reimbursementData.value.claimedAmount || 0,
      key: 'claimedAmount',
      type: 'currency',
    },
    {
      label: '费用类型',
      value: reimbursementData.value.receiptEvent || '-',
      key: 'receiptEvent',
    },
    {
      label: '申请状态',
      value: reimbursementData.value.status || '-',
      key: 'status',
      type: 'status',
    },
    {
      label: '审批状态',
      value: getStatusName('approvalStatus', reimbursementData.value.approvalStatus || 0) || '-',
      key: 'approvalStatus',
      type: 'status',
    },
  ]
})

// 创建人信息
const creatorInfo = computed<InfoItem[]>(() => {
  if (!reimbursementData.value)
    return []

  return [
    {
      label: '创建人',
      value: reimbursementData.value.createName || '-',
      key: 'createName',
    },
    {
      label: '创建时间',
      value: formatDate(reimbursementData.value.createTime, 'datetime_short'),
      key: 'createTime',
      type: 'datetime',
    },
    {
      label: '更新人',
      value: reimbursementData.value.updateName || '-',
      key: 'updateName',
    },
    {
      label: '更新时间',
      value: formatDate(reimbursementData.value.updateTime, 'datetime_short'),
      key: 'updateTime',
      type: 'datetime',
    },
  ]
})

// 页面加载时获取数据
onLoad((e: any) => {
  console.log('页面参数:', e)
  systemStore.fetchInvoiceTypeDict()
  console.log('发票类型字典:', systemStore.invoiceTypeDict)
  processInstanceId.value = e?.id || ''
  flowIdValue.value = e?.flowId || ''
  idValue.value = e?.id || ''
  if (processInstanceId.value) {
    fetchProcessInfo(processInstanceId.value)
  }
  else if (e?.businessId) {
    // 兼容直接使用业务ID的情况
    fetchReimbursementDetail(e.businessId)
  }
  else {
    uni.showToast({
      title: '页面参数错误',
      icon: 'none',
    })
  }
})

// 下拉刷新
onPullDownRefresh(async () => {
  // 如果有流程实例ID，通过流程刷新数据
  if (processInstanceId.value) {
    await fetchProcessInfo(processInstanceId.value)
  }
  // 如果只有业务ID，直接刷新详情数据
  else if (businessId.value) {
    await fetchReimbursementDetail()
  }
  uni.stopPullDownRefresh()
})
const tabValue = ref(0)
</script>

<template>
  <view class="overflow-hidden bg-gray-100 py-1">
    <!-- 加载状态 -->
    <view v-if="loading" class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center">
        <icons type="spinner-cycle" size="40" color="#409eff" class="animate-spin" />
        <text class="mt-4 text-gray-500">加载中...</text>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center p-6">
        <text class="mt-4 text-base text-gray-500">加载失败</text>
        <button
          class="mt-6 rounded-full bg-blue-500 px-6 py-2 text-white"
          @click="() => {
            if (businessId) {
              fetchReimbursementDetail(businessId)
            }
          }"
        >
          重新加载
        </button>
      </view>
    </view>

    <!-- 正常状态 -->
    <view v-else-if="reimbursementData" class="relative">
      <!-- 审批状态卡片 -->
      <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
      <wd-tabs v-model="tabValue" swipeable animated sticky :offset-top="0">
        <wd-tab title="基本信息" custom-class="bg-[#f9fafb]">
          <!-- 基本信息 -->
          <DetailCard
            title="基本信息"
            :info-list="basicInfo"
            class="mx-4 mt-4"
          />

          <!-- 报销信息 -->
          <DetailCard
            title="报销信息"
            :info-list="reimbursementInfo"
            class="mx-4 mt-4"
          />

          <!-- 创建人信息 -->
          <DetailCard
            title="创建人信息"
            :info-list="creatorInfo"
            class="mx-4 mb-6 mt-4"
          />
        </wd-tab>
        <wd-tab title="费用明细" custom-class="bg-[#f9fafb]">
          <!-- 费用明细列表 - 每个明细一个 DetailCard -->
          <view v-if="expenseDetailCards.length > 0" class="mx-4 mt-4">
            <view class="mb-3 flex items-center">
              <text class="text-lg text-gray-800 font-medium">费用明细</text>
              <text class="ml-2 text-sm text-gray-500">({{ expenseDetailCards.length }}条记录)</text>
            </view>

            <view v-for="(cardItems, index) in expenseDetailCards" :key="`expense-detail-card-${index}`" class="mb-4">
              <DetailCard
                :title="`费用明细 ${index + 1}`"
                :info-list="cardItems"
                :show-divider="false"
              >
                <template #invoiceAttachments="{ value }">
                  <view v-for="(item, i) in value" :key="`invoice-attachment-${i}`" class="mr-2 h-25 w-25 overflow-hidden border border-blue-200 rounded-2 border-solid">
                    <wd-img :src="item.filePath" lazy-load enable-preview mode="scaleToFill" class="h-full w-full" />
                  </view>
                </template>
              </DetailCard>
            </view>
          </view>
        </wd-tab>
      </wd-tabs>
    </view>

    <!-- 空状态 -->
    <view v-else class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center p-6">
        <wd-status-tip image="content" tip="暂无内容" />
      </view>
    </view>

    <!-- 审批操作栏 -->
    <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
  </view>
</template>

<style scoped>
/* 页面样式 */
.container {
  background-color: #f5f5f5;
  position: relative;
}

/* 加载动画 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式适配 */
/* #ifdef H5 */
.container {
  min-height: 100vh;
}
/* #endif */

/* #ifdef MP-WEIXIN */
.container {
  min-height: 100vh;
}
/* #endif */

/* #ifdef APP-PLUS */
.container {
  min-height: 100vh;
}
/* #endif */
</style>
